from rest_framework.permissions import BasePermission
import socket


class AllowLocalHost(BasePermission):
    """
    Allow any access.
    This isn't strictly required, since you could use an empty
    permission_classes list, but it's useful because it makes the intention
    more explicit.
    """

    def has_permission(self, request, view):
        """仅允许本机ip访问"""
        request_host = request.META.get("HTTP_X_FORWARDED_FOR") or request.META.get(
            "REMOTE_ADDR", ""
        )
        allowed_host = [
            "127.0.0.1",
            "localhost",
            socket.gethostbyname(socket.gethostname()),
        ]
        return request_host in allowed_host
